package org.bdware.irp.irpclient;

import io.netty.channel.Channel;
import org.apache.log4j.Logger;
import org.bdware.irp.irplib.core.IrpMessage;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;

public abstract class NettyIrpClientChannel implements IrpClientChannel {
    static Logger logger = Logger.getLogger(NettyIrpClientChannel.class);
    NettyIrpClientHandler handler;
    InetSocketAddress remoteAddress;
    boolean isConnected = false;
    Channel channel;

    public static IrpClientChannel createByServerUrl(String url) {
        try {
            URI uri = new URI(url);
            logger.debug("[URI Parse]scheme:" + uri.getScheme() + "  host: " + uri.getHost() + "  port: " + uri.getPort());
            switch (uri.getScheme()) {
                case "udp":
                case "UDP":
                case "tcp":
                case "TCP":
                    return new NettyIrpTCPClientChannel();
                default:
                    logger.error("unsupported transfer scheme");
                    return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void sendMessage(IrpMessage message, IrpMessageCallback cb){
        if(handler == null){
            logger.error("client handler not set yet");
            return;
        }
        if(!isConnected){
            logger.error("client not connected, connect first!");
        }

/*        if(GlobalCertifications.needAuthentication || GlobalCertifications.secureMode){
            try {
                CryptoUtils.signIrpMessage(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        message.header.setIsEncrypted(GlobalCertifications.secureMode);*/


/*        if(message.getSender() == null)
            message.setSender(remoteAddress);*/
        logger.debug("channel send message");
        handler.sendMessage(message,cb);
    };

    @Override
    abstract public void connect(String url) throws URISyntaxException;

    @Override
    public boolean isConnected(){return channel.isActive();}

}
